package com.lx.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.lx.bean.Admin;
import com.lx.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;

    @RequestMapping("/validateCode")
    public void validateCode(HttpServletRequest req, HttpServletResponse resp)throws Exception {
        //生成线条影响的验证码
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(200, 100);
        //获取线条生成的真正验证码
        String code = captcha.getCode();
        HttpSession session = req.getSession();
        session.setAttribute("realCode", code);
        //将验证码响应回浏览器
        OutputStream out = resp.getOutputStream();
        captcha.write(out);
    }

    @PostMapping("/login/{code}")
    public Map login2(@RequestBody Admin admin, @PathVariable("code") String code , HttpSession session){
        String realCode = (String)session.getAttribute("realCode");
        Map map = new HashMap();
        if(!code.equalsIgnoreCase(realCode)){
            map.put("msg","验证码有误");
            map.put("status","err");
            return map;
        }
        Admin login = adminService.login(admin.getUsername(),admin.getPassword());
        if(login == null){
            map.put("msg","用户名或密码有误");
            map.put("status","err");
            return map;
        }
        map.put("status","success");
        System.out.println(map.toString());
        return map;
    }

    @GetMapping("/admins")
    public Map showPageAdmins(@RequestParam(value = "page",defaultValue = "1") Integer page, @RequestParam(value = "limit",defaultValue = "5") Integer limit){
        Map map1 = adminService.showPageAdmin(page, limit);
        Map map = new HashMap();
        map.put("code",0);
        map.put("count",map1.get("count"));
        map.put("data",map1.get("admins"));
        return map;
    }
}
